#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cerrno>
#include <cassert>

using namespace std;
const int NUM = 1024;

int main()
{
    // 1.创建管道
    int pipefd[2] = {0};
    int ret = pipe(pipefd);
    if (ret < 0)
    {
        printf("pipe error, errno: %d ", errno);
        perror("The following error occurred");
        return 1;
    }

    // 2.创建子进程
    int id = fork();
    assert(id >= 0);

    // 3.关闭多余的fd
    if (id == 0)
    {
        // 子进程写

        close(pipefd[0]);

        int cnt = 0;
        char buf[NUM] = {0};
        while (true)
        {
            snprintf(buf, NUM - 1, "I am child, my pid is %d, counter: %d", getpid(), cnt++);
            write(pipefd[1], buf, strlen(buf));
            // write(pipefd[1], buf, sizeof(buf));
            //  if(cnt == 5)
            //  {
            //      break;
            //  }
            sleep(1);
        }

        close(pipefd[1]);

        exit(0);
    }

    // 父进程读

    close(pipefd[1]);

    char buf[NUM] = {0};
    while (true)
    {
        int n = read(pipefd[0], buf, sizeof(buf) - 1);
        if (n > 0)
        {
            buf[n] = '\0';
            cout << "我是父进程，子进程给我传递信息：" << buf << endl;
            if (buf[n - 1] == '5')
            {
                break;
            }
        }
        else if (n == 0)
        {
            cout << "文件读取到末尾了" << endl;
            break;
        }
        else
        {
            perror("The following error occurred");
            return 1;
        }
        sleep(1);
    }

    close(pipefd[0]);

    int status = 0;
    waitpid(id, &status, 0);
    cout << "sig: " << (status & 0x7f) << endl;

    return 0;
}